<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="IMEI" prop="mainboardId">
        <el-input
          v-model="queryParams.mainboardId"
          placeholder="请输入主板序列号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input
          v-model="queryParams.version"
          placeholder="请输入版本"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配置状态" prop="configStatus">
        <el-select v-model="queryParams.status" placeholder="请选择配置状态" clearable>
          <el-option
            v-for="item in configStatusOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="time">
        <el-date-picker clearable
          v-model="queryParams.time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gatewayManagement:airDetails:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gatewayManagement:airDetails:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gatewayManagement:airDetails:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="2" :push="4">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="small "
          :disabled="multiple"
          @click="handleConfig"
        >配置应用服务器</el-button>
      </el-col>
      <el-col :span="2" :push="6">
        <el-button
          type="warning"
          plain
          icon="el-icon-connection"
          size="small "
          @click="handleOTA"
        >OTA</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gatewayManagement:airDetails:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--   表格   -->
    <el-table v-loading="loading" :data="airDetailsList" @selection-change="handleSelectionChange"
              :border="true" :stripe="true" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主板ID" align="center" prop="mainboardId" >
        <template slot-scope="scope">
          <i class="el-icon-star-on" style="color:lightgreen;" v-if="scope.row.powerOnStatus == 0"></i>
          <i class="el-icon-star-on" style="color:info;" v-else></i>
          <span style="margin-left: 10px">{{ scope.row.mainboardId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="事件" align="center" prop="mainEvent" width="60" />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column label="上电时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="OTA" align="center" prop="networkInfo" >
        <template slot-scope="scope">
            <el-tag v-if=" scope.row.networkInfo != null " >{{scope.row.networkInfo}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配置状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag
            :type="statusTagType(scope.row.status)"
            effect="dark"
            style="min-width: 60px; text-align: center;"
          >
            {{ scope.row.status || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-view"
            @click="handleSelect(scope.row)"
            round
          >查询网关配置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改airDetails对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="主板ID" prop="mainboardId">
          <el-input v-model="form.mainboardId" placeholder="请输入主板ID" />
        </el-form-item>
        <el-form-item label="事件" prop="mainEvent">
          <el-input v-model="form.mainEvent" placeholder="请输入事件" />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker clearable
            v-model="form.time"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="ip地址" prop="networkInfo">
          <el-input v-model="form.networkInfo" placeholder="请输入ip地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--   mqtt  弹窗 -->
    <el-dialog :title="configTitle" @close="configClose" :visible.sync="configOpen" width="500px" append-to-body>
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="80px">
        <el-form-item label="服务器IP" prop="mqttIp">
          <el-input v-model="configForm.mqttIp" placeholder="请输入ip" :disabled="configDisabled" />
        </el-form-item>
        <el-form-item label="端口" prop="mqttPort">
          <el-input v-model="configForm.mqttPort" placeholder="请输入端口" :disabled="configDisabled"/>
        </el-form-item>
        <el-form-item label="用户名" prop="mqttName">
          <el-input v-model="configForm.mqttName" placeholder="请输入用户名" :disabled="configDisabled" show-password/>
        </el-form-item>
        <el-form-item label="密码" prop="mqttPw">
          <el-input v-model="configForm.mqttPw" placeholder="请输入密码" :disabled="configDisabled" show-password/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="configSubmitForm" :disabled="!configDisabled">确 定</el-button>
        <el-button @click="configCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  上传 文件 弹窗   -->
    <el-dialog :title="uploadTitle" @close="uploadClose" :visible.sync="uploadOpen" width="500px" append-to-body>
      <el-upload
        class="upload-demo"
        ref="aitFile"
        accept=".bin"
        :headers="airFile.headers"
        :action= "airFile.url"
        :on-preview="handlePreview"
        :on-success="handleSuccess"
        :on-change="handleChange"
        :limit= "1"
        :auto-upload="true"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip"> 每次只能上传（.bin）文件</div>
      </el-upload>
      <!--  单选   -->
      <div style="margin-top: 50px; margin-bottom: 30px;">
        <span style="font-weight: bold;">选择升级类型：</span>
        <el-radio v-model="radio" label="1" border >全量升级</el-radio>
        <el-radio v-model="radio" label="2" border >选定升级</el-radio>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadSubmitForm" >立即更新</el-button>
        <el-button :disabled= "radio==2" @click="uploadReservation">去预约</el-button>
      </div>
      <!--  内置 dialog 预约更新  -->
      <el-dialog width="30%" title="预约更新时间" :visible.sync="uploadInnerVisible" append-to-body>
        <el-form :label-position="labelPosition" label-width="80px"
                 :model="formReservation"  :rules="reserveRules" ref="formReservation"  >
          <el-form-item label="时间：" prop="reservationTime">
            <el-date-picker
              v-model="formReservation.reservationTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions" >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="事项：" prop="matter">
            <el-input  v-model="formReservation.matter"></el-input>
          </el-form-item>
          <el-form-item label="路径：" prop="downloadPath">
            <el-input v-model="formReservation.downloadPath" :disabled="true"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="reservationSubmitForm">确 定</el-button>
          <el-button @click="reservationCancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import { listAirDetails, getAirDetails, delAirDetails, addAirDetails, updateAirDetails,
        mqttConfigInfo, migrationService, selectGatewayConfigInfo, downloadFile, remoteOTA,
        reserveDownloadTask  } from "@/api/gatewayManagement/airDetails"
import {getToken} from "@/utils/auth.js";
export default {
  name: "AirDetails",
  data() {
    return {
      socket: null,
      radio: '1',    //  单选框
      // 选择时间 大于 现在时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() ;
        }
      },
      labelPosition: 'right',
      formReservation:{
        reservationTime: "",
        matter: "",
        downloadPath: ""
      },
      downloadPath: "",
      airFile:{
        type:".png",
        url: "http://192.168.3.9:8080/gatewayManagement/airDetails/uploadAirFile",
        headers: { Authorization: "Bearer " + getToken() },
      },
      configStatusOptions: [
        {
          value: '已配置',
        },
        {
          value: '未配置',
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //  选中 主板ID
      mainboardIdList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // airDetails表格数据
      airDetailsList: [],
      // 弹出层标题
      title: "",
      configTitle: "",
      uploadTitle: "",
      // 弹窗编辑状态
      configDisabled: true,
      // 是否显示弹出层
      open: false,
      configOpen: false,
      uploadOpen: false,
      uploadInnerVisible: false,   // 内层dialog
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        airDetailsId: null,
        mainboardId: null,
        mainEvent: null,
        version: null,
        time: null,
        networkInfo: null,
        status: null
      },
      // 表单参数
      form: {},
      configForm: {},
      // 表单校验
      rules: {
      },
      //  配置表单校验
      configRules: {},
      // 预约表单校验
      reserveRules:{
        reservationTime: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ],
        matter: [
          { required: true, message: '请输入事项', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getList()

    this.initWebSocket();
  },
  mounted() {

  },
  methods: {
    //  预约信息提交
    reservationSubmitForm(){
      this.$refs["formReservation"].validate(valid => {
        console.log(valid ,"---yuyue---", this.formReservation);
        if (valid){
          reserveDownloadTask(this.formReservation)
          .then(res =>{
            this.uploadInnerVisible = false;
            this.uploadOpen = false;
            this.$modal.msgSuccess("预约信息已上传")
          })
          .cancel(err =>{
              this.$message({
                      message: '上传预约信息失败',
                      type: 'error'
              });
          })
        }
      })
    },
    reservationCancel(){   // 预约取消
      this.uploadInnerVisible = false;
    },
    //  上传文件弹窗
    handleOTA(){
      this.uploadOpen = true;
      this.uploadTitle = "升级 OTA";
    },
    uploadClose(){
      this.downloadPath = null;
      this.radio = "1";
      this.$nextTick(() => {
        if (this.$refs.aitFile) {
          this.$refs.aitFile.clearFiles();
        }
      })
      this.getList();
    },
    uploadSubmitForm(row){
      const mainboardIds = [row.mainboardId || this.mainboardIdList].flat();
      console.log(this.radio ,"---选中---",mainboardIds)
      if (this.downloadPath == "" || this.downloadPath == null){
        return this.$message({
                  message: '请先上传（.bin）格式的文件',
                  type: 'error'
                });
      }
      const hasValidData = mainboardIds.some(item => item != null && item !== '');
      if (this.radio == 2){
        if (!hasValidData){
          return this.$message({
                  message: '请选择需要升级的主板',
                  type: 'error'
                })
        }
      }


      //  立即升级
      remoteOTA(this.downloadPath, mainboardIds, this.radio)
        .then(res => {
          this.uploadOpen = false;
          this.$modal.msgSuccess("开始发布订阅信息")
        })
        .catch(error => {
          this.$message({
                  message: '订阅失败',
                  type: 'error'
                });
        })
    },
    uploadReservation(){
      if (this.downloadPath == "" || this.downloadPath == null){
        return this.$message({
                message: '请先上传（.bin）格式的文件',
                type: 'error'
              });
      }
      this.uploadInnerVisible = true;
      this.formReservation.downloadPath = this.downloadPath;
    },
    handlePreview(file) {
      console.log("点击文件上传列表",file);
    },
    handleSuccess(response, file, fileList){
      console.log("--上传成功时---",response);
      if(response.code == 200){
        this.downloadPath = response.msg;
      } else {
        this.$message({
           message: '上传文件失败！',
           type: 'warning'
        });
      }
    },
    handleChange(file, fileList){
      console.log("文件改变",file, fileList);
    },
    // end
    extractStatus(status) {
      if (!status) return '';
      // 增强版提取逻辑
      const match = status.match(/[\u4e00-\u9fa5]+/);
      return match?.[0] || status;
    },
    statusTagType(status) {
        const pureStatus = this.extractStatus(status);
        console.log("--------",pureStatus)
        const statusMap = {
          '已配置': 'success',
          '未配置': 'info',
        };
        return statusMap[pureStatus] || '';
      },
    handleSelect(row){
      const mainboardIds = [row.mainboardId || this.mainboardIdList].flat();
      console.log(mainboardIds ,"---配置信息---",row);
      this.$message({
          message: '等待完善',
          center: true
        });
      // selectGatewayConfigInfo(mainboardIds)
    },
    //
    handleConfig(){
      console.log("----点击配置---")
      mqttConfigInfo()
        .then( res => {
          this.configForm = res.data[0]
          this.configOpen = true;
          this.configTitle = "MQTT服务器配置信息";
        })
        .catch( err =>{
          this.$message({
                  message: '获取配置信息失败',
                  type: 'error'
                });
        })
    },
    configSubmitForm(row){
      const mainboardIds = [row.mainboardId || this.mainboardIdList].flat();
      console.log("---主板ID ---", mainboardIds)
      migrationService(mainboardIds)
        .then( res => {
          this.$modal.msgSuccess("发布配置订阅成功")
          this.configOpen = false
          this.getList()
        })
        .catch(err => {
          this.$message({
                  message: '发布配置订阅失败',
                  type: 'error'
                });
        })
    },
    configCancel(){
      this.configOpen = false;
      this.configReset();
    },
    configClose(){
      console.log("--点击关闭了---");
      this.configReset();
      this.getList();
    },
    // configUpdate(){
    //   this.configDisabled = false;
    // },
    /** 查询airDetails列表 */
    getList() {
      this.loading = true
      listAirDetails(this.queryParams).then(response => {
        this.airDetailsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        mainboardId: null,
        mainEvent: null,
        version: null,
        time: null,
        networkInfo: null,
        status: null
      }
      this.resetForm("form")
    },
    //  配置信息表单重置
    configReset(){
      this.configForm = {
        configId :null,
        msgType: null,
        mqttIp: null,
        mqttPort: null,
        mqttName: null,
        mqttPw: null,
        msgId: null,
        status: null
      }
      this.configDisabled = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.mainboardIdList = selection.map( item => item.mainboardId)
      this.ids = selection.map(item => item.airDetailsId)
      this.single = selection.length!== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加airDetails"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const airDetailsId = row.airDetailsId || this.ids
      getAirDetails(airDetailsId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改airDetails"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.airDetailsId != null) {
            updateAirDetails(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAirDetails(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const airDetailsIds = row.airDetailsId || this.ids
      const mainboardIds = [row.mainboardId || this.mainboardIdList].flat();
      this.$modal.confirm('是否确认删除airDetails编号为"' + mainboardIds + '"的数据项？').then(function() {
        return delAirDetails(airDetailsIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gatewayManagement/airDetails/export', {
        ...this.queryParams
      }, `airDetails_${new Date().getTime()}.xlsx`)
    },
    //  websocket
    initWebSocket() {
      const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
      const host = "192.168.3.9:8080";
      this.socket = new WebSocket( protocol + host +"/websocket");
      this.socket.onmessage = (event) => {
        console.log('收到消息:', event.data);
        this.$modal.msgSuccess( event.data);

        if(event.data.slice(0, 4) == "升级成功"){
          this.getList()
        }
      };
      this.socket.onclose = () => {
        console.log('连接关闭');
        this.$modal.msgError( " websocket 连接关闭 ");
      };
      this.socket.onerror = () =>{
         this.$modal.msgError( " websocket 发送错误 ");
      };
    },
    //  websocket 发送消息
    sendMessage() {
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send("前端发送了一条消息");
      }
    }
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  }

}
</script>

<style>
  /* 解决 el-radio 报错 Blocked aria-hidden... 问题 */
 input[aria-hidden="true"] {
      display: none !important;
  }
  .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
      box-shadow: none;
  }
  /*         end         */
</style>
